package com.heima.leetcode.practice;

/**
 * @author 勾新杰
 * @version 1.0
 * @description: leetcode 58. 最后一个单词的长度
 * @date 2025/5/11 11:32
 */
public class E58 {
    public int lengthOfLastWord(String s) {
        char[] charArray = s.toCharArray();
        boolean hasStr = false;
        int length = 0;
        for (int i = charArray.length - 1; i >= 0; i--) {
            char c = charArray[i];
            if (c == ' ' && hasStr) {
                return length;
            } else if (c != ' ') {
                length++;
                hasStr = true;
            }
        }
        return length;
    }

    public String lastWord(String s) {
        char[] charArray = s.toCharArray();
        boolean hasStr = false;
        StringBuilder builder = new StringBuilder();
        for (int i = charArray.length - 1; i >= 0; i--) {
            char c = charArray[i];
            if (c == ' ' && hasStr) {
                return reverse(builder.toString());
            } else if (c != ' ') {
                builder.append(c);
                hasStr = true;
            }
        }
        return reverse(builder.toString());
    }

    private String reverse(String string) {
        char[] charArray = string.toCharArray();
        int left = 0;
        int right = charArray.length - 1;
        while (left < right) {
            char temp = charArray[left];
            charArray[left] = charArray[right];
            charArray[right] = temp;
            left++;
            right--;
        }
        return new String(charArray);
    }
}
